package cn.wolfcode.shop.mq;

import cn.wolfcode.shop.consts.MQConstents;
import cn.wolfcode.shop.mq.msg.CreateOrderMsg;
import cn.wolfcode.shop.mq.msg.SeckillSuccessDelayMsg;
import cn.wolfcode.shop.mq.msg.SeckillSuccessMsg;
import cn.wolfcode.shop.service.IOrderInfoService;
import com.alibaba.druid.sql.dialect.oracle.visitor.OracleEvalVisitor;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(
        topic = MQConstents.SECKILL_ORDER_TOPIC,
        selectorExpression = MQConstents.SECKILL_ORDER_TAG,
        consumerGroup = MQConstents.SECKILL_ORDER_CONSUMER_GROUP
)
@Slf4j
public class CreateSeckillOrderMQListener implements RocketMQListener<CreateOrderMsg> {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public void onMessage(CreateOrderMsg msg) {
        log.info("接收到创建秒杀订单的消息：", JSON.toJSONString(msg));

        try {
            // 调用创建秒杀订单的接口，执行秒杀操作
            String orderNo = orderInfoService.doSeckill(msg.getSeckillId(), msg.getUserId());

            // 如果调用创建订单成功，表示订单创建成功，发送消息提示用户
            rocketMQTemplate.syncSend(MQConstents.SECKILL_SUCCESS_DEST,
                    new SeckillSuccessMsg(msg.getUuid(), orderNo));



            // 发送延迟消息：在订单创建成功之后，创建并发送一个延迟消息，这个延迟消息会在30分钟之后被消费
            GenericMessage<SeckillSuccessDelayMsg> message = new GenericMessage<>(
                    new SeckillSuccessDelayMsg(msg.getSeckillId(), orderNo));
            // 发送消息，设置时间等级: 等级18个：messageDelayLevel=1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
            rocketMQTemplate.syncSend(MQConstents.SECKILL_SUCCESS_DELAY_DEST, message, 5000, 16);



        } catch (Exception e) {
            // 如果调用创建订单出现异常，表示订单创建失败，需要做下面的操作
            e.printStackTrace();
            // 1. 发送订单创建失败的消息，通知用户
            rocketMQTemplate.syncSend(MQConstents.SECKILL_FAILED_DEST, msg.getUuid());
            // 2. 回补Redis中的库存，MySQL有事务，数据不会有变化，不需要回补
            // 3. 清除本地售完标记
            orderInfoService.handlerFailedseckill(msg.getSeckillId());
        }
    }
}
